import os
import sys
import zipfile
import hashlib


def calculate_md5(file_path):
    """计算文件的MD5值（支持大文件分块读取）[5,8,10](@ref)"""
    md5_hash = hashlib.md5()
    with open(file_path, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b""):
            md5_hash.update(chunk)
    return md5_hash.hexdigest()


def zip_folder(src_dir, zip_name):
    """压缩文件夹并保持目录结构[3,6,7](@ref)"""
    with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, _, files in os.walk(src_dir):
            # 计算相对路径
            relative_path = os.path.relpath(root, src_dir)
            for file in files:
                file_path = os.path.join(root, file)
                arcname = os.path.join(relative_path, file) if relative_path != '.' else file
                zipf.write(file_path, arcname=arcname)


def main():
    if len(sys.argv) != 3:
        print("用法：python script.py <文件夹路径> <版本号>")
        sys.exit(1)

    folder_path = sys.argv[1]
    version = sys.argv[2]

    if not os.path.isdir(folder_path):
        print(f"错误：{folder_path} 不是有效目录")
        sys.exit(1)

    # 生成初始ZIP文件名
    base_name = os.path.basename(folder_path.rstrip('/\\'))
    initial_zip = f"{base_name}_temp.zip"

    try:
        # 执行压缩
        zip_folder(folder_path, initial_zip)
        print(f"已创建临时压缩包：{initial_zip}")

        # 计算MD5
        md5_value = calculate_md5(initial_zip)
        print(f"MD5校验值：{md5_value}")

        # 生成最终文件名
        final_name = f"{base_name}_{version}_{md5_value}.zip"
        os.rename(initial_zip, final_name)
        print(f"重命名成功：\n{initial_zip} -> {final_name}")

    except Exception as e:
        print(f"操作失败：{str(e)}")
        if os.path.exists(initial_zip):
            os.remove(initial_zip)
        sys.exit(1)


if __name__ == "__main__":
    main()